package com.template.cms.auth.service;

import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.template.auth.mapper.GroupMapper;
import com.template.auth.mapper.UserGroupMapper;
import com.template.auth.model.Group;
import com.template.auth.model.GroupExample;
import com.template.auth.model.UserGroup;
import com.template.auth.model.UserGroupExample;
import com.template.auth.utils.Page;
import com.template.auth.utils.SystemContext;
import com.template.cms.auth.exception.CMSException;

@Service("groupService")
public class GroupService implements IGroupService {
	
	@Inject
	private GroupMapper groupMapper;
	
	
	@Inject
	private UserGroupMapper userGroupMapper;
	

	@Override
	public void add(Group group) {
		groupMapper.insertSelective(group);

	}

	@Override
	public void delete(int id) {
		UserGroupExample userGroupExample = new UserGroupExample();
		userGroupExample.createCriteria().andGIdEqualTo(id);
		List<UserGroup> userGroup = userGroupMapper.selectByExample(userGroupExample);
		if(userGroup.size() > 0) throw new CMSException("删除的用户组中还有用户，不能删除");
		groupMapper.deleteByPrimaryKey(id);

	}

	@Override
	public Group load(int id) {
		return groupMapper.selectByPrimaryKey(id);
	}

	@Override
	public void update(Group group) {
		groupMapper.updateByPrimaryKeySelective(group);

	}

	@Override
	public List<Group> listGroup() {
		GroupExample groupExample = new GroupExample();
		return groupMapper.selectByExample(groupExample);
	}

	@Override
	public Page<Group> findGroup() {
		Page<Group> page = new Page<Group>(SystemContext.getPageOffset(),SystemContext.getPageSize());
		GroupExample groupExample = new GroupExample();
		page.setTotalRecords(groupMapper.countByExample(groupExample));
		groupExample.setOrderByClause(SystemContext.getSort()+" "+SystemContext.getOrder());
		groupExample.setPage(page);
		page.setPageDatas(groupMapper.selectByExample(groupExample));
		return page;
	}

	@Override
	public void deleteGroupUsers(int gid) {
		UserGroupExample userGroupExample = new UserGroupExample();
		userGroupExample.createCriteria().andGIdEqualTo(gid);
		userGroupMapper.deleteByExample(userGroupExample);
	}

}
